package com.tingyuge.thinking.spring.event;

import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * @author xiaodao
 * @version 1.0
 * @date 2021/12/13
 * @description
 */
public class HierarchicalSpringEventDemo {

    public static void main(String[] args) {
        //1.创建 parent spring 应用上下文
        AnnotationConfigApplicationContext parentApplication = new AnnotationConfigApplicationContext();
        parentApplication.setId("parent-context");
        parentApplication.register(MyListener.class);
        //2.创建当前上下文
        AnnotationConfigApplicationContext currentApplication = new AnnotationConfigApplicationContext();
        currentApplication.setId("current-context");
        //3.current-->parent
        currentApplication.setParent(parentApplication);

        //4.注册 myListener 到 current spring 应用上下文
        currentApplication.register(MyListener.class);

        //5.启动应用上下文
        parentApplication.refresh();
        //refreshedEvent
        currentApplication.refresh();
        //startedEvent
        currentApplication.start();

        // stoppedEvent
        currentApplication.stop();
        //closedEvent
        currentApplication.close();
        parentApplication.close();



    }

    static class MyListener implements ApplicationListener<ApplicationContextEvent>{
        //静态字段是应该俩个需要共享
        private static Set<ApplicationContextEvent> processEvents = new LinkedHashSet<>();

        @Override
        public void onApplicationEvent(ApplicationContextEvent event) {
            if(processEvents.add(event)){
                System.out.printf("监听到 Spring 应用上下文 [ID %s] 的 ApplicationContextEvent %s \n",event.getApplicationContext().getId(),event);
            }

        }
    }

}
